<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box {
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>

<body>
  <div id="box"></div>
  <button id="btn1">计算</button>
  <button id="btn2">改颜色</button>
  <script>
    const box = document.getElementById('box')
    const btn1 = document.getElementById('btn1')
    const btn2 = document.getElementById('btn2')

    let count = 10000
    let value = 0

    function calc(idleDeadline) {
      // 当剩余时间大于1时才执行
      while (count > 0 && idleDeadline.timeRemaining() > 1) {
        console.log(11)
        value = Math.random() < 0.4 ? Math.random() : Math.random()
        count--
      }
      // 再次去申请浏览器空余时间执行
      requestIdleCallback(calc)
    }

    btn1.onclick = () => {
      // 申请浏览器空余时间执行calc计算方法
      requestIdleCallback(calc)
    }
    btn2.onclick = () => {
      box.style.backgroundColor = 'green'
    }
  </script>
</body>

</html>